<?php

use DocBoot\Application;
use DocBoot\Controller\ExceptionRenderer;
use DocBoot\Controller\HookInterface;
use DocBoot\Controller\ResponseRenderer;
use DocBoot\Docgen\Swagger\Swagger;
use FastRoute\Dispatcher;
use support\Request;
use Webman\Route;

$app = Application::createByDefault([
    ResponseRenderer::class => \DI\create(support\docboot\ResponseRenderer::class),
    ExceptionRenderer::class => \DI\create(support\docboot\ExceptionRenderer::class)
]);
$controllerPaths = config('plugin.yesgooo.docboot.conf.controllerPath');
foreach ($controllerPaths as $fromPath => $namespace) {
    $app->loadRoutesFromPath($fromPath, $namespace);
}
if(function_exists('envs') && envs('APP_ENV') === 'dev') {
    $swaggerConfig = config('plugin.yesgooo.docboot.conf.swagger', []);
    Route::add('GET', '/apiDoc/swagger.json', function ()use($app, $swaggerConfig) {
        $swagger = new Swagger();
        $swagger->appendControllers($app, $app->getControllers());
        $swagger->schemes = [$swaggerConfig['schemes'] ?? 'http'];
        $swagger->host = $swaggerConfig['host'] ?? 'your host';
        $swagger->info->title = $swaggerConfig['title'] ?? '文档标题';
        $swagger->info->description = $swaggerConfig['description'] ?? '此文档为 swagger 格式的 json, 请使用Swagger UI 渲染成 web。';
        $swagger->externalDocs = new \DocBoot\Docgen\Swagger\Schemas\ExternalDocumentationObject();
        $swagger->externalDocs->description = '';
        $swagger->externalDocs->url = '';
        return response($swagger->toJson(),200, ['Content-Type'=>'application/json;charset=utf-8']);
    });
}
foreach ($app->getRoutes() as $route) {
    list($method, $uri, $handler, $hooks) = $route;
    $next = function (\Symfony\Component\HttpFoundation\Request $request) use ($handler, $method, $uri, $app) {

        /**------start 解析路由参数---------------*/
        $uri = $request->getRequestUri();
        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }
        $uri = rawurldecode($uri);

        $dispatcher = $app->getDispatcher();
        $res = $dispatcher->dispatch($method, $uri);
        if ($res[0] == Dispatcher::FOUND) {
            if (count($res[2])) {
                $request->attributes->add($res[2]);
            }
        }
        /**------end 解析路由参数-----------------*/

        return $handler($request);
    };
    foreach (array_reverse($hooks) as $hookName){
        $next = function($request)use($app, $hookName, $next){
            $hook = $app->get($hookName);
            /**@var $hook HookInterface*/
            return $hook->handle($request, $next);
        };
    }
    Route::add(
        $method,
        '/' . $uri,
        function(Request $request) use ($next) {
            $requestProxy = \Symfony\Component\HttpFoundation\Request::create(
                $request->uri(),
                $request->method(),
                $request->all(),
                $request->cookie(),
                $request->file(),
                [],
                $request->post()
            );
            $requestProxy->headers = new \Symfony\Component\HttpFoundation\HeaderBag($request->header());
            return $next($requestProxy);
        }
    );
}

Route::disableDefaultRoute();
